package com.neusoft.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.neusoft.entity.Pay;
import com.neusoft.entity.Rent;
import com.neusoft.entity.Room;
import com.neusoft.entity.common.CommonResult;
import com.neusoft.service.PayService;
import com.neusoft.service.RentService;
import com.neusoft.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

@Controller
@RequestMapping("rent")
public class RentController {
    /**
     * 服务对象
     */
    @Resource
    @Autowired
    private RentService rentService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private PayService payService;

    @GetMapping("queryById/{id}")
    @ResponseBody
    public Object queryById(@PathVariable Integer id){
        System.out.println("查询单条数据"+id);
        Rent bean = rentService.queryById(id);
        System.out.println("bean对象为："+bean);
        return bean;
    }

    @PostMapping("deleteById/{ids}")
    @ResponseBody
    public boolean deleteById(@PathVariable Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return false;
        }
        for (int i=0;i<ids.length;i++){
            Rent bean = rentService.queryById(ids[i]);
            Room bean1 = roomService.queryById(bean.getHouseid());
            bean1.setBool("待出租");
            roomService.update(bean1);
        }
        System.out.println("批量删除数据");
        System.out.println(ids[0]);
        rentService.deleteById(Arrays.asList(ids));
        return true;
    }

    @PostMapping("deleteById1/{id}")
    @ResponseBody
    public boolean deleteById1(@PathVariable Integer id) {
        System.out.println("删除单条数据");
        if ( id == null) {
            return false;
        }
        Rent rent = (Rent) queryById(id);
        System.out.println("根据房屋编号退房处理："+rent.getHouseid());
        Room room;
        room = roomService.queryById(rent.getHouseid());
        room.setBool("待出租");
        roomService.update(room);
        return rentService.deleteById1(id);
    }

    @PostMapping("queryAll/{page}/{limit}")
    @ResponseBody
    public Object queryAll(@PathVariable Integer page, @PathVariable Integer limit, @RequestBody Rent bean) {
        System.out.println(page);
        System.out.println(limit);
        System.out.println(bean);
        CommonResult<Rent> result = new CommonResult<>();
        IPage<Rent> ipage = rentService.queryAllByLimit(page, limit, bean);
        result.setCode(0);
        result.setCount(ipage.getTotal());
        result.setData(ipage.getRecords());
        System.out.println("数据查询成功");
        System.out.println(result);
        return result;
    }

    @PutMapping("save")
    @ResponseBody
    public Object save(@RequestBody Rent bean) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("修改和添加数据");
        boolean result = false;
        //判断账号是否存在
        //判断是添加还是修改
        if (bean.getId() != null) {
            result = rentService.update(bean) > 0;
        }
        else if(bean.getAmount() != null){
            boolean result1 = false;
            Room room = new Room();
            room = roomService.queryById(bean.getHouseid());
            room.setBool("已出租");
            result1 = roomService.update(room) > 0;
            result = rentService.insert(bean).getId() != null;

            //出租后添加客户欠租信息
            Integer amount = bean.getAmount();
            String name = bean.getName();

            Date d = bean.getRentdate();
            String dateString1 = sdf.format(d);
            Date newDate1 =sdf.parse(dateString1);//将字符串转换为时间格式
            java.sql.Date resultDate1 = new java.sql.Date(newDate1.getTime());
            java.util.Date time;
            time = sdf.parse(sdf.format(new Date()));
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(resultDate1);
            c2.setTime(time);
            int year1 = c1.get(Calendar.YEAR);
            int year2 = c2.get(Calendar.YEAR);
            int month1 = c1.get(Calendar.MONTH);
            int month2 = c2.get(Calendar.MONTH);
            int day1 = c1.get(Calendar.DAY_OF_MONTH);
            int day2 = c2.get(Calendar.DAY_OF_MONTH);
            // 获取年的差值 
            int yearInterval = year1 - year2;
            // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
            if (month1 < month2 || month1 == month2 && day1 < day2) {
                yearInterval--;
            }
            // 获取月数差值
            int monthInterval = (month1 + 12) - month2;
            if (day1 < day2) {
                monthInterval--;
            }
            monthInterval %= 12;
            int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
            if(monthsDiff > 0){
                Pay pay = new Pay();
                pay.setName(name);
                pay.setAmount(amount);
                pay.setTotal(monthsDiff*amount);
                pay.setState("已欠租");
                payService.insert(pay);
            }else if(monthsDiff == 0){
                Pay pay1 = new Pay();
                pay1.setName(name);
                pay1.setAmount(amount);
                pay1.setTotal(amount);
                pay1.setState("已欠租");
                payService.insert(pay1);
            }

            //满约自动删除数据退房处理
            Date d1;
            d1 = bean.getRentdate();
            String dateString = sdf.format(d1);
            System.out.println("格式转换前："+d1);
            Date newDate =sdf.parse(dateString);//将字符串转换为时间格式
            java.sql.Date resultDate = new java.sql.Date(newDate.getTime());
            System.out.println("格式转换后："+resultDate);
            String datestr = resultDate.toString();
            System.out.println("转换字符串后："+datestr);
            String[] ymd = datestr.split("-");
            Calendar c;
            long endTime;
            long startTime;
            long midTime;
            c = Calendar.getInstance();
            c.set(Integer.parseInt(ymd[0]), (Integer.parseInt(ymd[1]))-1, Integer.parseInt(ymd[2]), 0,0,0);
            endTime = c.getTimeInMillis();
            Date date1 = new Date();
            startTime = date1.getTime();
            midTime = (endTime - startTime) / 1000;
            Integer houseid = bean.getHouseid();
            System.out.println("时间差为："+midTime);
            int result2;
            while (midTime > 0) {
                String str;
                midTime--;
                long dd = midTime / 60 / 60 / 24;
                long hh = midTime / 60 / 60 % 24;
                long mm = midTime / 60 % 60;
                long ss = midTime % 60;
                str = "还剩" + dd + "天" + hh + "小时" + mm + "分钟" + ss + "秒自动退房";
                System.out.println(str);
                System.out.println(houseid);
                Rent rent1 = rentService.queryByHouseId(houseid);
                System.out.println("根据房屋编号查找："+rent1);
                rent1.setRemark(str);
                result2 = rentService.update(rent1);
                try {
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            //租约到期后自动退房并删除对应租赁信息
            room = roomService.queryById(bean.getHouseid());
            room.setBool("待出租");
            roomService.update(room);
            rentService.deleteByHouseId(bean.getHouseid());
        }
        else {
            result = rentService.insert(bean).getId() != null;
        }
        return result;
    }

    @PutMapping("checkin/{id}")
    @ResponseBody
    public boolean checkin(@PathVariable  Integer id){
        Rent rent = rentService.queryById(id);
        rent.setState("是");
        int result = rentService.update(rent);
        return true;
    }

}
